package com.llb666.java.leetcode;

/**
 * 给一个整数数组，找出长度为k平均数最大的连续子数组，并输出最大平均数
 * Created by 斌~
 * 2021/4/29 15:23
 */
public class 子数组最大平均数 {
    public static void main(String[] args) {
        int[] arr = {1,5,7,8,3,-1,6,24};
        System.out.println(findMaxAverage(arr,4));
    }

    /**
     * 滑动窗口算法
     *    | 1 5 7 8| 3 -1 6 4
     *   1 | 5 7 8 3 | -1 6 4
     */
    private static double findMaxAverage(int[] nums,int k){
        int sum = 0;
        int n = nums.length;
        //初始化窗口和
        for (int i = 0; i < k; i++) {
            sum+=nums[i];
        }
        int max = sum;
        //窗口右移
        for (int i = k; i < n; i++) {
            sum  = sum - nums[i-k]+nums[i];
            max = Math.max(sum, max);
        }
        return 1.0*max/k;
    }
}
